package com.huayi.server.NioServer;

import com.huayi.server.Entity.DeviceEntity;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class MessageDecode extends ByteToMessageDecoder {

    Logger logger = LoggerFactory.getLogger(MessageDecode.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Message message = new Message();
        int length = in.readableBytes();

        //logger.info("length:"+length);

        //log(in);

        message.setLen(in.readShort());
        message.setKey(in.readUnsignedByte());
        message.setAck(in.readUnsignedByte());
        message.setApi(in.readUnsignedByte());
        switch (message.getApi()){
            case 2:
                message.setData_len(in.readUnsignedByte());
                ByteBuf deviceslist = in.readBytes(message.getData_len() * 10 );
                List<DeviceEntity> list = new ArrayList<>();
                for (int i=0;i<message.getData_len();i++){
                    DeviceEntity deviceEntity = new DeviceEntity();
                    byte[] bytes = new byte[4];
                    deviceslist.readBytes(bytes);
                    deviceEntity.setDeviceId(new String(bytes));
                    deviceEntity.setOnline(deviceslist.readByte()==2);
                    deviceEntity.setOpen(deviceslist.readByte()==2);
                    deviceEntity.setBattery((float) deviceslist.readUnsignedByte());
                    deviceEntity.setHum((float) deviceslist.readUnsignedByte());
                    short tmp = deviceslist.readShort();
                    deviceEntity.setTmp((float) (tmp!=0?tmp/10-50:0));
                    list.add(deviceEntity);
                }
                message.setDevicelist(list);
                break;
            case 4:
                ByteBuf info = in.readBytes(10);
                String id = info.readUnsignedByte()+""+info.readUnsignedByte()+""+info.readUnsignedByte()+""+info.readUnsignedByte();
                message.setDeviceid(id);
                byte[] pass = new byte[6];
                info.readBytes(pass);
                message.setDevicepass(new String(pass));
                break;
            case 5:
                break;
        }
        message.setCrc(in.readUnsignedByte());
        logger.info(message.toString());
        out.add(message);
    }

    private void log(ByteBuf in){
        byte[] bytess = new byte[in.readableBytes()];
        in.readBytes(bytess);

        StringBuilder x = new StringBuilder();
        for (byte b : bytess) {
            String z = String.format(" %02x",b);
            x.append(z);
        }
        logger.info(x.toString());
    }
}
